<template>
    <div class="user" style="margin: 20px;">
        <!-- 行内表单 -->
        <el-form :inline="true">
            <el-form-item>
                <el-input v-model="tempSearchObj.username" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
                <el-button type="default" @click="empty">清空</el-button>
            </el-form-item>
        </el-form>
        <el-button type="primary" @click="add" v-if="$hasBP('btn.User.add')">添 加</el-button>
        <el-button type="danger" @click="batchDel" :disabled = "multipleSelectionIds.length===0" v-if="$hasBP('btn.User.remove')">批量删除</el-button>
        <el-dialog :title="userForm.id ? `修改用户` : `添加用户`" :visible.sync="dialogFormVisible"
            :close-on-click-modal="false">
            <el-form :model="userForm" :rules="rules" ref="userForm" style="width: 90%" label-width="100px"
                class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickName">
                    <el-input v-model="userForm.nickName"></el-input>
                </el-form-item>
                <el-form-item v-if="!userForm.id" label="密码" prop="password">
                    <el-input v-model="userForm.password"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- table表格 -->
        <div style="margin-top: 20px">
            <el-table tooltip-effect="dark" style="width: 100%" border @selection-change="handleSelectionChange"
                :data="urlList">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column label="序号" type="index" width="80" align="center">
                </el-table-column>
                <el-table-column prop="username" label="用户名" width="120">
                </el-table-column>
                <el-table-column prop="nickName" label="用户昵称">
                </el-table-column>
                <el-table-column prop="roleName" label="角色列表">
                </el-table-column>
                <el-table-column prop="gmtCreate" label="创建时间">
                </el-table-column>
                <el-table-column prop="gmtModified" label="更新时间">
                </el-table-column>
                <el-table-column label="操作" width="230" align="center">
                    <template slot-scope="{row,$index}">
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start">
                            <el-button type="info" icon="el-icon-user-solid" size="mini" title="分配角色"
                                @click="distributionRole(row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="修改用户" placement="top-start">
                            <el-button type="primary" size="mini" icon="el-icon-edit" title="修改用户"
                                @click="amend(row, $index)"></el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除用户" placement="top-start">
                            <el-popconfirm :title="`确定删除 ${row.username}吗?`" @onConfirm="deluser(row.id)">
                                <el-button style="margin-left:10px" slot="reference" size="mini" type="danger"
                                    title="删除用户" icon="el-icon-delete"></el-button>
                            </el-popconfirm>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 设置角色弹框 -->
            <el-dialog title="设置角色" :visible.sync="assignroles" :close-on-click-modal="false">
                <el-form ref="form" :model="form" label-width="80px" :disabled="false">
                    <el-form-item label="用户名">
                        <el-input disabled :value="userForm.username"></el-input>
                    </el-form-item>
                    <!-- 多选框 -->
                    <el-form-item label="角色列表">
                        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">
                            全选
                        </el-checkbox>
                        <div style="margin: 15px 0;"></div>
                        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                            <el-checkbox v-for="city in cities" :label="city.id" :key="city.id">{{ city.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="cancel(2)">取 消</el-button>
                    <el-button type="primary" @click="saveRoles">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <!-- 分页 -->
        <div style="margin-top: 20px">
            <el-pagination :current-page="page" :total="total" :page-size="limit" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" :page-sizes="[5, 10, 15]" :pager-count="7"
                layout=" prev, pager, next, jumper,->,sizes,total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep';
export default {

    data() {
        return {
            searchObj: { // 包含请求搜索条件数据的对象
                username: ''
            },
            tempSearchObj: { // 收集搜索条件输入的对象
                username: ''
            },
            dialogFormVisible: false,
            urlList: [],   // 列表展示数据
            assignroles: false,  //是否显示角色Dialog
            userForm: {    //弹框的列表展示
                username: '',
                nickName: '',
                password: ''
            },
            form: {
                name: ''
            },
            // 表单校验
            rules: {
                username: [
                    { required: true, message: '用户名必须输入', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password: [
                    // { required: true, message: '密码必须输入', trigger: 'blur' },
                    // { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
                    { required: true, validator: this.validatePassword }
                ],
            },
            checkAll: false,   //是否全选
            checkedCities: [],  //选中角色
            isIndeterminate: true,   //是否是不确定的
            cities: [],   //角色列表
            page: 1, //分页器第几页
            limit: 5, //当前页展示数据条数
            total: 0, //总共数据条数
            loading: false,  // 是否正在提交请求中
            listLoading: false,//是否显示列表加载的提示
            multipleSelectionIds:[] // 所有选择的user的id的数组
        }
    },
    mounted() {
        this.getUserList()
    },
    methods: {
        // 获取列表数据
        async getUserList() {
            this.listLoading = true
            try {
                const { page, limit, searchObj } = this
                let result = await this.$API.user.getPageList(page, limit, searchObj)
                console.log(result)
                this.urlList = result.data.items
                this.total = result.data.total
                this.listLoading = false
            } catch (error) {
                console.error(error)
            }
        },
        // 查询
        search() {
            this.searchObj = { ...this.tempSearchObj }
            this.getUserList()
        },
        // 清空
        empty() {
            this.searchObj = {
                username: ''
            },
                this.tempSearchObj = {
                    username: ''
                }
            this.getUserList()
        },
        // 添加
        add() {
            this.dialogFormVisible = true
            // 清除数据
            this.userForm = { username: '', nickName: '', password: '' }
        },
        // 批量删除
        batchDel(){
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
        await  this.$API.user.removeUsers(this.multipleSelectionIds)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
        // 修改
        amend(row, $index) {
            this.dialogFormVisible = true
            this.userForm = cloneDeep(row)
        },
        // 删除
        async deluser(id) {
            await this.$API.user.removeById(id)
            this.$message.success('删除成功')
            this.getUserList(this.userForm.length === 1 ? this.page - 1 : this.page)
        },
        // 分配角色
        distributionRole(userForm) {
            this.userForm = userForm
            this.assignroles = true
            this.getRoles()
        },
        // 获取某个用户的所有角色
        async getRoles() {
            try {
                let result = await this.$API.user.getRoles(this.userForm.id)
                const { allRolesList, assignRoles } = result.data
                this.cities = allRolesList
                this.checkedCities = assignRoles.map(item => item.id)
                this.checkAll = allRolesList.length === assignRoles.length
                this.isIndeterminate = assignRoles.length > 0 && assignRoles.length < allRolesList.length
                // console.log(result)
            } catch (error) {
                console.error(error)
            }
        },
        // 角色全选
        handleCheckAllChange(val) {
            this.checkedCities = val ? this.cities.map(item => item.id) : []
            this.isIndeterminate = false;
        },
        // 角色单选
        handleCheckedCitiesChange(value) {
            // console.log(value)
            let checkedCount = value.length;   //角色列表的数组长度
            this.checkAll = checkedCount === this.cities.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
        },
        // 给用户进行角色分配
        async saveRoles() {
            const userId = this.userForm.id
            const cities = this.checkedCities.join(',')
            // console.log(userId,cities)
            this.loading = true
            try {
                let result = await this.$API.user.assignRoles(userId, cities)
                console.log(result)
                this.loading = false
                this.$message.success(result.message || '分配角色成功')
                this.assignroles = false
                this.resetRoleData()
            } catch (error) {
                console.error(error)
            }
        },
        // 重置用户角色的数据
        resetRoleData() {
            // this.assignroles = false
            this.allRoles = []
            this.checkedCities = []
            // this.isindeterminate = false
            this.checkAll = false
        },
        // 自定义校验密码
        validatePassword(rule, value, callback) {
            if (!value) {
                callback('密码必须输入')
            } else if (!value || value.length < 6) {
                callback('密码不能小于6位')
            } else {
                callback()
            }
        },
        // 确定
        addOrUpdate() {
            this.$refs.userForm.validate(async (success) => {
                console.log(success)
                if (success) {
                    try {
                        this.dialogFormVisible = false
                        if (!this.userForm.id) {
                            await this.$API.user.add(this.userForm)
                        } else {
                            await this.$API.user.update(this.userForm)
                        }
                        this.$message({
                            message: this.userForm.id ? '保存成功' : '添加成功',
                            type: 'success'
                        })
                        this.getUserList()
                    } catch (error) {
                        console.error(error)
                    }
                } else {
                    console.log('确定按钮失败');
                    return false;
                }
            });
        },
        // 取消
        cancel(type) {
            if (type === 1) {
                this.dialogFormVisible = false
                this.userForm = {}
            } else {
                this.assignroles = false
            }
        },
        // 表格
        handleSelectionChange(val) {
            this.multipleSelectionIds = val.length > 0 ? val.map(item =>item.id) :val.id;
        },
        // 分页 每页条数发生变化时候触发
        handleSizeChange(limit) {
            this.limit = limit
            this.getUserList()
        },
        // 当前页数函数
        handleCurrentChange(page) {
            // 修改参数
            this.page = page
            this.getUserList()

        },
    }
}

</script>

<style  scoped>

</style>